﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
using Bussiness.Manager;
using Bussiness.Entity;
using AF_ORM.CORE;
using System.Collections;

namespace DSC.uc
{
    public partial class ucRoleFunction : AfUserControl
    {
        int isChangedData = 0;
        public Hashtable hshNotActiveFunction = new Hashtable();
        public ucRoleFunction()
        {
            InitializeComponent();
            LoadData();
        }

        protected void LoadData()
        {
            ShowStatusBar("Đang load dữ liệu");
            LoadRoleTree();
            LoadFormTree();
            treeRole.NodeMouseClick += new TreeNodeMouseClickEventHandler(treeRole_NodeMouseClick);
            treeRoleFunction.AfterCheck += new TreeViewEventHandler(treeRoleFunction_AfterCheck);
            btnSave.Visible = false;
            EndShowStatusBar();
        }

      

        void treeRoleFunction_AfterCheck(object sender, TreeViewEventArgs e)
        {
          
            foreach (TreeNode node in e.Node.Nodes)
            {
                node.Checked = e.Node.Checked;
            }
            isChangedData = 1;
        }

      

        void treeRole_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            
            if (e.Node.Tag == null)
                return;
            foreach (TreeNode node in treeRole.Nodes[0].Nodes)
                node.ForeColor = Color.Black;
            
            e.Node.ForeColor = Color.Red;
            if (isChangedData == 1 && AF.Library.FNumber.IsDecimal(lblRoleId.Text) && btnSave.Visible == true)
            {
                if (MessageBox.Show("Dữ liệu đã thay đổi, bạn có muôn lưu lại?", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    btnSave_Click(null, null);
                }
            }
            //LoadFunctionByRole(e.Node.Tag);
            object roleId = e.Node.Tag;
            if (roleId != null && AF.Library.FNumber.IsDecimal(roleId.ToString()))
            {
                DataTable tblRoleFunc = PT_Role_FunctionManager.CreateInstant().SelectByRoleId(int.Parse(roleId.ToString()));
                for (int i = 0; i < treeRoleFunction.Nodes.Count; i++)
                {
                    
                    treeRoleFunction.Nodes[i].Checked = false;
                    LoadFunctionByRole(treeRoleFunction.Nodes[i], roleId, tblRoleFunc);
                }
                
                btnSave.Visible = true;
            }
            else
            {
                for (int i = 0; i < treeRoleFunction.Nodes.Count; i++)
                {
                    treeRoleFunction.Nodes[i].Checked = false;
                }
            }
            lblRoleName.Text = e.Node.Text;
            lblRoleId.Text = e.Node.Tag.ToString();
            isChangedData = 0;
           
        }

        protected void LoadFunctionByRole(TreeNode node, object roleId, DataTable tblRoleFunc)
        {
            if (node.Tag != null && AF.Library.FNumber.IsDecimal(node.Tag.ToString()))
            {
                node.Checked = tblRoleFunc.Select("FunctionId='" + node.Tag + "'").Length > 0;
            }
            foreach (TreeNode child in node.Nodes)
            {
                LoadFunctionByRole(child, roleId, tblRoleFunc);
            }
        }

        protected void LoadFormTree()
        {
            SelectOptions option1 = new SelectOptions();
            option1.AddSortField("OrderIndex", true);
            List<PT_FormEntity> lst = PT_FormManager.CreateInstant().SelectAllLST(option1);
            treeRoleFunction.Nodes.Clear();
            TreeNode nodeFunction = new TreeNode("Chức năng");
            nodeFunction.Checked = false;
            
            treeRoleFunction.Nodes.Add(nodeFunction);
            for (int i = 0; i < lst.Count; i++)
            {
                TreeNode node = new TreeNode(lst[i].FormTitle);
                node.Tag = lst[i].FormName;
                nodeFunction.Nodes.Add(node);
                SelectOptions option = new SelectOptions();
                option.AddSortField("Tag",true);
                List<PT_FunctionEntity> lstFunc = PT_FunctionManager.CreateInstant().SelectByFormNameLST(lst[i].FormName,option);
                for (int j = 0; j < lstFunc.Count; j++)
                {
                    //neu chuc nang nay khong active (khong can dung phan quyen) thi khong hien len tree ma luu vao hashtable.
                    //khi luu xuong thi lay cac gia tri trong hastable de luu xuong cung voi cac gia tri check trong tree.
                    if (!lstFunc[j].IsActive)
                    {
                        hshNotActiveFunction.Add(lstFunc[j].FunctionId, lstFunc[j].FunctionId);
                    }
                    else
                    {
                        TreeNode nodeChild = new TreeNode(lstFunc[j].Tag);
                        nodeChild.Tag = lstFunc[j].FunctionId;
                        node.Nodes.Add(nodeChild);
                    }
                }
            }
            nodeFunction.ExpandAll();
        }

        protected void LoadRoleTree()
        {
            /*
            System.Windows.Forms.TreeNode treeNode1 = new System.Windows.Forms.TreeNode("Node1");
            System.Windows.Forms.TreeNode treeNode2 = new System.Windows.Forms.TreeNode("Node2");
            System.Windows.Forms.TreeNode treeNode3 = new System.Windows.Forms.TreeNode("Chức năng", new System.Windows.Forms.TreeNode[] {
            treeNode1,
            treeNode2});
            System.Windows.Forms.TreeNode treeNode4 = new System.Windows.Forms.TreeNode("Node1");
            System.Windows.Forms.TreeNode treeNode5 = new System.Windows.Forms.TreeNode("Node2");
            System.Windows.Forms.TreeNode treeNode6 = new System.Windows.Forms.TreeNode("Quyền", new System.Windows.Forms.TreeNode[] {
            treeNode4,
            treeNode5});

            treeNode1.Checked = true;
            treeNode1.Name = "Node1";
            treeNode1.Text = "Node1";
            treeNode2.Checked = true;
            treeNode2.Name = "Node2";
            treeNode2.Text = "Node2";
            treeNode3.Name = "Node0";
            treeNode3.Text = "Chức năng";
             */

            
            /*
            treeNode4.Checked = true;
            treeNode4.Name = "Node1";
            treeNode4.Text = "Node1";
            treeNode5.Checked = true;
            treeNode5.Name = "Node2";
            treeNode5.Text = "Node2";
            treeNode6.Name = "Node0";
            treeNode6.Text = "Quyền";
            this.treeRole.Nodes.AddRange(new System.Windows.Forms.TreeNode[] {
            treeNode6});
             */
            treeRole.Nodes.Clear();
            TreeNode nodeRole = new TreeNode("Danh sách quyền");
            nodeRole.Checked = false;
            
            treeRole.Nodes.Add(nodeRole);

            List<PT_RoleEntity> lst = PT_RoleManager.CreateInstant().SelectAllLST();
            for (int i = 0; i < lst.Count; i++)
            {
                TreeNode node = new TreeNode(lst[i].RoleName.ToString());
                node.Tag = lst[i].RoleId;
                nodeRole.Nodes.Add(node);
            }
            nodeRole.ExpandAll();
          
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            ShowStatusBar("Đang lưu dữ liệu");
            string tag = lblRoleId.Text;
            if (AF.Library.FNumber.IsDecimal(tag))
            {
                int roleId = int.Parse(tag);
                //xoa cac function cu
                PT_Role_FunctionManager.CreateInstant().DeleteByRoleId(roleId);
                SaveFunction(roleId, treeRoleFunction.Nodes[0]);
                //Luu cac function mac dinh 
                SaveNotActiveFunction(roleId);
                isChangedData = 0;
                MessageBox.Show("Đã lưu dữ liệu");
            }
        }
        private void SaveNotActiveFunction(int roleId)
        {
            //luu cac gia tri tren hashtable
            foreach (DictionaryEntry entry in hshNotActiveFunction)
            {
                PT_Role_FunctionEntity obj = new PT_Role_FunctionEntity();
                obj.RoleId = roleId;
                obj.FunctionId = int.Parse(entry.Key.ToString());
                PT_Role_FunctionManager.CreateInstant().Insert(obj);
            }
        }

        private void SaveFunction(int roleId,  TreeNode node)
        {
            //luu cac gia tri check tren tree
            if (node.Checked && node.Tag != null)
            { 
                string tag = node.Tag.ToString();
                if (AF.Library.FNumber.IsDecimal(tag))
                {
                    int functionId = int.Parse(tag);
                    PT_Role_FunctionEntity obj = new PT_Role_FunctionEntity();
                    obj.RoleId = roleId;
                    obj.FunctionId = functionId;
                    PT_Role_FunctionManager.CreateInstant().Insert(obj);
                }
            }
            foreach (TreeNode child in node.Nodes)
            {
                SaveFunction(roleId, child);
            }
            
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            string RoleName = "";
            if (MessageBox.Show("Bạn thật sự muốn xóa các quyền được chọn ?", "Cảnh báo", MessageBoxButtons.OKCancel, MessageBoxIcon.Warning) == DialogResult.OK)
            {
                ShowStatusBar("Đang xóa dữ liệu");
                foreach (TreeNode node in treeRole.Nodes[0].Nodes)
                {
                    if (node.Checked)
                    {
                        String roleId = node.Tag.ToString();
                        PT_AccountEntity option = new PT_AccountEntity();
                        option.RoleId = int.Parse(roleId);
                        option.IsDeleted = false;
                        DataTable dt = PT_AccountManager.CreateInstant().SelectWithCondition(option);
                        if (dt.Rows.Count > 0)
                        {
                            if (!string.IsNullOrEmpty(RoleName))
                                RoleName += ", ";
                            RoleName += node.Text;
                        }
                        else
                            PT_RoleManager.CreateInstant().DeleteByRoleId(int.Parse( roleId));
                    }
                }
                if (!string.IsNullOrEmpty(RoleName))
                {
                    MessageBox.Show("Hiện đang có user thuộc các quyền (" + RoleName + ") nên bạn không thể xóa các quyền này.");
                }
                LoadRoleTree();
                EndShowStatusBar();
            }
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            frmRoleDetail frm = new frmRoleDetail();
            this.ShowChildForm(frm);
        }

        public override void Search()
        {
            ShowStatusBar("Đang tìm kiếm");
            LoadRoleTree();
            EndShowStatusBar();
        }
    }
}
